package com.taobao.itest.casegen;

import com.taobao.itest.casegen.domain.Rule;
import com.taobao.itest.casegen.domain.RuleHouse;
import com.taobao.itest.casegen.util.AgentRunnable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 * User: cangfeng.mxf
 * Date: 12-9-14
 * Time: 上午11:37
 * To change this template use File | Settings | File Templates.
 */
@Component
public class RuleReceiver {
    /**存储连接上来的socket下的规则*/
    @Resource
    private RuleHouse store;

    public static final int PORT = 48881;
    /**与客户端交互的ServerSocket对讲机, 接收客户端socket*/
    private ServerSocket intercom;

    /**处理客户请求的线程池*/
    private ExecutorService executor;
    //默认线程个数为5
    private int threadNum = 5;
    //是否停止终端
    private boolean stop = false;

    @PostConstruct
    public void init() throws IOException {
        intercom = new ServerSocket(PORT, 0, InetAddress.getLocalHost());
        executor = Executors.newFixedThreadPool(threadNum);
    }

    public void setThreadNum(int num){
        threadNum = num;
    }
    public void stop(){
        stop = true;
    }

    public int getThreadNum(){
        return threadNum;
    }
    public boolean isStop(){
        return stop;
    }

    public void start(){
        while(true){
            if(stop == true){
                break;
            }
            try{
                //收到连接过来的socket了
                Socket sock = intercom.accept();
                //分配一个线程去处理, Server端继续处理其他的请求
                Runnable task = new AgentRunnable(sock);
                executor.execute(task);
                if(null == rules.get(String.valueOf(sock.getPort()))){
                    ArrayList<Rule> ruleList = new ArrayList<Rule>();
                    ruleList.add(new Rule(getInput(sock)));
                }
            }catch(IOException ioEx){
                ioEx.printStackTrace();
            }
        }
    }

    /**获取客户端输入的*/
    private String getInput(Socket socket){
        return null;
    }
}
